import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:message_tools/application.dart';
import 'package:message_tools/components/appbar_plugins.dart';
import 'package:message_tools/components/button.dart';
import 'package:message_tools/components/file_manager.dart';
import 'package:message_tools/model/sms_task.dart';
import 'package:message_tools/model/sms_template.dart';
import 'package:message_tools/store/index.dart';
import 'package:message_tools/store/view_model/sms_task_model.dart';
import 'package:message_tools/ui/page/sms/select_sms_template_page.dart';
import 'package:message_tools/utils/date_utils.dart';

const buttonHeight = 50.0;
const rightButtonHeight = 40.0;

/// ListView 默认的实例,无状态
class AddSmsTaskPage extends StatefulWidget {
  AddSmsTaskPage();

  @override
  _AddSmsTaskPageState createState() => _AddSmsTaskPageState();
}

class _AddSmsTaskPageState extends State<AddSmsTaskPage> {
  TextEditingController _titleCtrl = new TextEditingController();
  FocusNode _contentFocusNode = FocusNode();
  BuildContext _context;

  SmsTask _smsTask = SmsTask();
  String _contactFilePath = "";
  String _smsTemplateTitle = "";
  String _smsTemplateContent = "";
  String _preMessage = "";

  void initData() async {
    var json = await Application.getString("edit_sms_task");
    debugPrint("initData ====== json $json \n");

    if (json == null || json == "") {
      return;
    }

    setState(() {
      var map = Application.jsonDecode(json);
      _smsTask = SmsTask.fromJsonMap(map);
      _titleCtrl.text = _smsTask.title;
      _contactFilePath = _smsTask.contactFilePath;
      _smsTemplateTitle = _smsTask.smsTemplateTitle;
      _smsTemplateContent = _smsTask.smsTemplateContent;
      _preMessage = SmsTaskModel.computedPreMessage(_smsTask, null);
    });
  }

  @override
  void initState() {
    initData();
    super.initState();
  }

  Widget build(BuildContext context) {
    _context = context;

    return Scaffold(
      appBar: AppBarPlugin.Create("新增发送任务", centerTitle: true,
          leading: Builder(builder: (BuildContext c) {
        return IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () {
              Navigator.pop(context);
            });
      })),
      body: Theme.of(context).platform == TargetPlatform.iOS
          ? CupertinoScrollbar(
              child: _buildBody(),
            )
          : Scrollbar(
              child: _buildBody(),
            ),
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
        child: Column(
      children: <Widget>[
        createTitleView(),
        createContactButtons(),
        createSelectSmsTemplateButton(),
        createSubmitButton(),
        createPreviewMessage(),
      ],
    ));
  }

  Container createTitleView() {
    return Container(
        child: Row(
      children: <Widget>[
        Expanded(
          child: TextField(
            controller: _titleCtrl,
            decoration: new InputDecoration(
              icon: Icon(Icons.title),
              hintText: "请输入发送任务名称",
              helperText: '请输入发送任务名称',
            ),
          ),
        )
      ],
    ));
  }

  Row createContactButtons() {
    return Row(children: <Widget>[
      Expanded(
          child: Container(
        padding: const EdgeInsets.only(left: 5, top: 5),
        alignment: Alignment.center,
        child: Text("联系人:"),
      )),
      Expanded(
          flex: 2,
          child: Container(
            padding: const EdgeInsets.only(left: 5, top: 5),
            alignment: Alignment.center,
            child: Text(_contactFilePath),
          )),
      //Expanded(child: Container()),
      /*Expanded(
          child: Container(
        padding: const EdgeInsets.only(left: 5, top: 5),
        alignment: Alignment.center,
        child: createButton(
            height: buttonHeight,
            fontSize: 16,
            text: "从通讯录选择",
            minWidth: double.infinity,
            backgroundColor: Colors.deepOrangeAccent,
            onPressed: () {}),
      )),*/
      Expanded(
          child: Container(
        padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
        alignment: Alignment.center,
        child: createButton(
            height: buttonHeight,
            fontSize: 14,
            text: "从文件导入",
            minWidth: double.infinity,
            backgroundColor: Colors.deepOrangeAccent,
            onPressed: () async {
              var sDCardDir = await Application.getString("sDCardDir");
              Navigator.push(
                context,
                new MaterialPageRoute(
                    builder: (ctx) => FileManager(sDCardDir: sDCardDir)),
              ).then((value) async {
                var filepath =
                    await Application.getString("_contactFilePath") ?? "";
                if (filepath == "") {
                  return;
                }

                setState(() {
                  _contactFilePath = filepath;
                });
              });
            }),
      )),
    ]);
  }

  Row createSelectSmsTemplateButton() {
    return Row(children: <Widget>[
      Expanded(
          flex: 1,
          child: Container(
            padding: const EdgeInsets.only(left: 5, top: 5),
            alignment: Alignment.center,
            child: Text("短信模板:"),
          )),
      Expanded(
          flex: 2,
          child: Container(
            padding: const EdgeInsets.only(left: 5, top: 5),
            alignment: Alignment.centerLeft,
            child: Text(_smsTemplateTitle),
          )),
      Expanded(
          flex: 1,
          child: Container(
            padding: const EdgeInsets.only(left: 5, right: 5, top: 5),
            alignment: Alignment.center,
            child: createButton(
                height: buttonHeight,
                fontSize: 14,
                text: "选择模板",
                minWidth: double.infinity,
                backgroundColor: Colors.deepOrangeAccent,
                onPressed: () {
                  Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (ctx) => SelectSmsTemplatePage()),
                  ).then((json) {
                    var map = Application.jsonDecode(json);
                    var smsTemplate = SmsTemplate.fromJsonMap(map);
                    setState(() {
                      _smsTemplateTitle = smsTemplate.title;
                      _smsTemplateContent = smsTemplate.content;
                      _smsTask.contactFilePath = _contactFilePath;
                      _smsTask.smsTemplateTitle = _smsTemplateTitle;
                      _smsTask.smsTemplateContent = _smsTemplateContent;
                      _preMessage =
                          SmsTaskModel.computedPreMessage(_smsTask, null);
                    });
                  });
                }),
          )),
    ]);
  }

  Row createSubmitButton() {
    return Row(
      children: <Widget>[
        Expanded(
          child: Container(
              padding: const EdgeInsets.only(left: 5, top: 5, right: 5),
              alignment: Alignment.center,
              child: createButton(
                  height: buttonHeight,
                  text: "保存任务",
                  minWidth: double.infinity,
                  backgroundColor: Colors.green,
                  onPressed: () async {
                    _contentFocusNode.unfocus();

                    if (!validatorForm(
                        _titleCtrl.text, _contactFilePath, _smsTemplateTitle)) {
                      return;
                    }

                    _smsTask.title = _titleCtrl.text;
                    _smsTask.contactFilePath = _contactFilePath;
                    _smsTask.smsTemplateTitle = _smsTemplateTitle;
                    _smsTask.smsTemplateContent = _smsTemplateContent;
                    _smsTask.createdAt =
                        DateUtil.formatNowTime("yyyy-MM-dd HH:mm");

                    Store.value<SmsTaskModel>(context).save(_smsTask);
                    Navigator.pop(context);

                    // Navigator.popAndPushNamed(context, "/sms_task_list_page");
                  })),
        )
      ],
    );
  }

  bool validatorForm(String title, String contact, String template) {
    if (title.length == 0) {
      mAlertDialog(_context, "任务名称不能为空!");
      return false;
    }

    if (contact.length == 0) {
      mAlertDialog(_context, "联系人不能为空!");
      return false;
    }

    if (template.length == 0) {
      mAlertDialog(_context, "短信模板不能为空!");
      return false;
    }

    return true;
  }

  Container createPreviewMessage() {
    return Container(
        //margin: new EdgeInsets.all(5),
        width: double.infinity,
        padding: new EdgeInsets.all(40),
        decoration: new BoxDecoration(
            /*color: Color(0xFFebebf3),
                borderRadius: new BorderRadius.circular(10.0)),*/
            image: DecorationImage(
          image: AssetImage("assets/images/sms_bg.png"),
          fit: BoxFit.fill,
        )),
        child: new LimitedBox(
          maxWidth: MediaQuery.of(context).size.width,
          child: Text(_preMessage,
              softWrap: true,
              overflow: TextOverflow.ellipsis,
              maxLines: 100,
              textAlign: TextAlign.left,
              style: new TextStyle(height: 1, fontSize: 20)),
        ));
  }

  void mAlertDialog(BuildContext context, String content) {
    showDialog(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('系统提示'),
          content: Text(content),
          actions: <Widget>[
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
          elevation: 20,
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        );
      },
    );
  }

  void selectFileDialog() {
    showDialog(
      context: _context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('系统提示'),
          content: new SingleChildScrollView(
            child: new ListBody(
              children: <Widget>[
                new Text('内容 1'),
                new Text('内容 2'),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
          elevation: 20,
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        );
      },
    );
  }
}
